package com.example.demo;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: class辅助类
 *
 * @Author zhourunjin
 * @Date 2024/4/16 09:59
 */
@Slf4j
public class RuleClassUtils<T> {

//    private static final Map<String, DynamicClassLoader> CLASSLOADER_MAP = new ConcurrentHashMap<>(16);

    private static final String CLASS_PATH_BUNDLE_CONTENT = "rulegenerate";
    private static final String CLASS_PATH;
    private static final DynamicClassLoader CLASS_LOADER = new DynamicClassLoader();


    static {
        String tmpDirPath = System.getProperty("java.io.tmpdir");
        String dirName = "credit_rule_service";
        CLASS_PATH = tmpDirPath + File.separator + dirName;

        File directory = new File(CLASS_PATH);
        // 检查目录是否存在
        if (directory.exists()) {
            boolean delete = directory.delete();
            log.info("删除临时目录结果:{}", delete);
        }
        // 如果目录不存在，则创建目录
        boolean created = directory.mkdir();
        if (created) {
            log.info("目录已创建：{}", CLASS_PATH);
        } else {
            log.info("无法创建目录：{}", CLASS_PATH);
        }

    }

    public static String getClassPath() {
        return CLASS_PATH;
    }

    public static Class<?> forName(String className) throws ClassNotFoundException, NullPointerException {
        if (className == null) {
            throw new NullPointerException("className is null");
        }
        if (!className.contains(CLASS_PATH_BUNDLE_CONTENT)) {
            return Class.forName(className);
        }
        return Class.forName(className, true, CLASS_LOADER);
    }

//    public static DynamicClassLoader getClassloader(String className) throws ClassNotFoundException {
//        // 不是自定义类, 不用做处理
//        if (!className.contains(CLASS_PATH_BUNDLE_CONTENT)) {
//            return null;
//        }
//        return CLASSLOADER_MAP.computeIfAbsent(className, key -> new DynamicClassLoader());
//    }
//
//    public static void updateClassloader(String className) throws ClassNotFoundException {
//        // 不是自定义类, 不用做处理
//        if (!className.contains(CLASS_PATH_BUNDLE_CONTENT)) {
//            return ;
//        }
//        CLASSLOADER_MAP.put(className, new DynamicClassLoader());
//    }

}
